﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Drawing;
using Microsoft.SharePoint;

namespace Adartse.Sharepoint.WebPartEditors
{
    public class ListRepeaterEditor: EditorPart
    {
        private DropDownList _ddlLists;
        private DropDownList _ddlViews; //new
        private DropDownList _ddlTypes;
        private TextBox _tbxEditor;
        private TextBox _tbxID;
        private TextBox _tbxClass;
        private CheckBox _chkID;
        private CheckBox _chkClass;
        private CheckBox _chkViews;  //new
        private TextBox _tbxItems;
        private TextBox _tbxHeader;

        private TextBox _tbxEmptyTemplate;

        public ListRepeaterEditor()
        {
            this.Title = "List Repeater Configuration";
        }

        public override bool ApplyChanges()
        {
            this.EnsureChildControls();
            AWPListRepeater wp = (AWPListRepeater)this.WebPartToEdit;

            wp.ListName = _ddlLists.SelectedValue;
            wp.HtmlContent = _tbxEditor.Text;
            wp.ContainterID = _tbxID.Text;
            wp.ContainerClass = _tbxClass.Text;
            wp.IsIDEnabled = _chkID.Checked;
            wp.IsClassEnabled = _chkClass.Checked;
            wp.ContainerType = _ddlTypes.SelectedIndex;
            wp.HeaderContent = _tbxHeader.Text;
            wp.IsByView = _chkViews.Checked;
            wp.ViewName = _ddlViews.SelectedValue;

            wp.EmptyTemplate = _tbxEmptyTemplate.Text;

            wp.FieldList = ValidateFields(_tbxEditor.Text, new Guid(_ddlLists.SelectedValue));
            return true;
        }

        public override void SyncChanges()
        {
            this.EnsureChildControls();
            AWPListRepeater wp = (AWPListRepeater)this.WebPartToEdit;

            _chkClass.Checked = wp.IsClassEnabled;
            _chkID.Checked = wp.IsIDEnabled;
            _tbxClass.Text = wp.ContainerClass;
            _tbxID.Text = wp.ContainterID;
            _ddlLists.SelectedValue = wp.ListName;
            _tbxEditor.Text = wp.HtmlContent;
            _ddlTypes.SelectedIndex = wp.ContainerType;
            _tbxHeader.Text = wp.HeaderContent;

            _tbxEmptyTemplate.Text = wp.EmptyTemplate;

            _chkViews.Checked = wp.IsByView;
            if (wp.IsByView)
                _ddlViews.SelectedValue = wp.ViewName;
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            _ddlLists = new DropDownList();
            _ddlTypes = new DropDownList();
            _tbxEditor = new TextBox();
            _tbxID = new TextBox();
            _tbxClass = new TextBox();
            _chkID = new CheckBox();
            _chkClass = new CheckBox();
            _tbxItems = new TextBox();
            _tbxHeader = new TextBox();

            _ddlViews = new DropDownList();
            _chkViews = new CheckBox();

            _tbxEmptyTemplate = new TextBox();
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            try
            {
                _ddlLists.ID = "ddlListNames";
                _ddlLists.Width = new Unit(100, UnitType.Percentage);
                _ddlLists.AutoPostBack = true;
                _ddlLists.EnableViewState = true;

                _ddlViews.ID = "ddlViews";
                _ddlViews.Width = new Unit(80, UnitType.Percentage);
                _ddlViews.EnableViewState = true;

                _tbxItems.ID = "tbxItems";
                _tbxItems.Width = new Unit(100, UnitType.Percentage);
                _tbxItems.Height = new Unit(200);
                _tbxItems.EnableViewState = true;
                _tbxItems.TextMode = TextBoxMode.MultiLine;
                _tbxItems.ReadOnly = true;


                _ddlTypes.ID = "ddlTypes";
                _ddlTypes.Width = new Unit(100, UnitType.Percentage);
                _ddlTypes.AutoPostBack = true;
                _ddlTypes.EnableViewState = true;

                _chkID.ID = "chkID";
                _chkID.Text = "ID";
                _chkID.EnableViewState = true;

                _tbxID.ID = "tbxID";
                _tbxID.EnableViewState = true;

                _chkClass.ID = "chkClass";
                _chkClass.Text = "Class";
                _chkClass.EnableViewState = true;

                _tbxClass.ID = "tbxClass";
                _tbxClass.EnableViewState = true;

                _tbxHeader.ID = "tbxHeaderContent";
                _tbxHeader.Width = new Unit(100, UnitType.Percentage);
                _tbxHeader.Height = new Unit(100);
                _tbxHeader.TextMode = TextBoxMode.MultiLine;
                _tbxHeader.EnableViewState = true;

                _tbxEditor.ID = "tbxEditor";
                _tbxEditor.Width = new Unit(100, UnitType.Percentage);
                _tbxEditor.Height = new Unit(200);
                _tbxEditor.TextMode = TextBoxMode.MultiLine;
                _tbxEditor.EnableViewState = true;

                _tbxEmptyTemplate.ID = "tbxEmptyTemplate";
                _tbxEmptyTemplate.Width = new Unit(100, UnitType.Percentage);
                _tbxEmptyTemplate.Height = new Unit(200);
                _tbxEmptyTemplate.TextMode = TextBoxMode.MultiLine;
                _tbxEmptyTemplate.EnableViewState = true;
                

                _chkViews.ID = "chkViews";
                _chkViews.Text = "By View:";
                _chkViews.EnableViewState = true;
                _chkViews.AutoPostBack = true;

                Controls.Add(_ddlLists);
                Controls.Add(_tbxItems);
                Controls.Add(_ddlTypes);
                Controls.Add(_chkID);
                Controls.Add(_tbxID);
                Controls.Add(_chkClass);
                Controls.Add(_tbxClass);
                Controls.Add(_tbxHeader);
                Controls.Add(_tbxEditor);

                Controls.Add(_ddlViews);
                Controls.Add(_chkViews);

                Controls.Add(_tbxEmptyTemplate);

                if (_ddlLists.Items.Count == 0)
                {
                    FillData();
                }
            }
            catch (Exception ex)
            {
                Controls.Add(new LiteralControl(ex.ToString()));
            }
        }

        private void FillData()
        {
            _ddlTypes.Items.AddRange(GetEnumItems());
            _ddlLists.Items.AddRange(GetLists());
        }

        protected override void OnPreRender(EventArgs e)
        {
            Guid guid = Guid.Empty;
            if (!string.IsNullOrEmpty(_ddlLists.SelectedValue))
                guid = new Guid(_ddlLists.SelectedValue);

            if (!guid.Equals(Guid.Empty))
            {
                _ddlViews.Items.Clear();
                _ddlViews.Items.AddRange(GetViews(guid));
                _tbxItems.Text = string.Join( Environment.NewLine, GetListItem(guid));

                if (_chkViews.Checked)
                {
                    _ddlViews.Enabled = true;
                    _ddlViews.BackColor = Color.White;
                }
                else
                {
                    _ddlViews.Enabled = false;
                    _ddlViews.BackColor = Color.FromKnownColor(KnownColor.InactiveCaption);
                }
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            string startTag = "";
            string endTag = "";
            switch (_ddlTypes.SelectedIndex)
            {
                case 0:
                    startTag = "<div>";
                    endTag = "</div>";
                    break;
                case 1:
                    startTag = "<tr>";
                    endTag = "</tr>";
                    break;
                case 2:
                    startTag = "<il>";
                    endTag = "</il>";
                    break;
                default:
                    break;
            }
            //Title
            writer.RenderBeginTag(HtmlTextWriterTag.Strong);
            writer.Write("Available List:");
            writer.RenderEndTag();
            writer.WriteBreak();
            //List Control
            _ddlLists.RenderControl(writer);
            writer.WriteBreak();
            //Views
            _chkViews.RenderControl(writer);
            writer.WriteEncodedText(" ");
            _ddlViews.RenderControl(writer);
            writer.WriteBreak();
            //Title
            writer.RenderBeginTag(HtmlTextWriterTag.Strong);
            writer.Write("Fields:");
            writer.RenderEndTag();
            writer.WriteBreak();
            //Items
            _tbxItems.RenderControl(writer);
            writer.WriteBreak();
            //Tittle
            writer.RenderBeginTag(HtmlTextWriterTag.Strong);
            writer.Write("Container Type:");
            writer.RenderEndTag();
            writer.WriteBreak();
            //Container Types
            _ddlTypes.RenderControl(writer);
            writer.WriteBreak();
            //Container ID
            _chkID.RenderControl(writer);
            _tbxID.RenderControl(writer);

            _chkClass.RenderControl(writer);
            _tbxClass.RenderControl(writer);
            //Title
            writer.WriteBreak();
            writer.RenderBeginTag(HtmlTextWriterTag.Strong);
            writer.Write("Header Template");
            writer.RenderEndTag();
            //Header
            _tbxHeader.RenderControl(writer);
            writer.WriteBreak();
            //Title
            writer.RenderBeginTag(HtmlTextWriterTag.Strong);
            if (!string.IsNullOrEmpty(startTag))
                writer.WriteEncodedText(startTag);
            else
                writer.WriteEncodedText("Item Template");
            writer.RenderEndTag();
            //Editor
            _tbxEditor.RenderControl(writer);
            writer.WriteBreak();
            //Title
            writer.RenderBeginTag(HtmlTextWriterTag.Strong);
            writer.Write("Empty Template");
            writer.RenderEndTag();
            writer.WriteBreak();
            //Editor Template
            _tbxEmptyTemplate.RenderControl(writer);

            if (!string.IsNullOrEmpty(endTag))
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Strong);
                writer.WriteEncodedText(startTag);
                writer.RenderEndTag();
            }


            if (!Page.IsPostBack)
                FillData();
        }

        private ListItem[] GetLists()
        {
            List<ListItem> li = new List<ListItem>();
            foreach (SPList list in SPContext.Current.Web.Lists)
                li.Add(new ListItem(list.Title, list.ID.ToString()));

            return li.ToArray();
        }

        private string[] GetListItem(Guid id)
        {
            List<string> li = new List<string>();
            SPList list = SPContext.Current.Web.Lists.GetList(id, false); ;
            if (list != null)
            {
                SPFieldCollection fields = list.Fields;
                foreach (SPField field in fields)
                {
                    li.Add((string.Format("{0} [{1}]", field.Title, field.InternalName)));
                }
            }
            return li.ToArray();
        }

        private ListItem[] GetEnumItems()
        {
            return Enum.GetNames(typeof(ListRepeaterRenderTypeEnum)).Select(i => new ListItem(i)).ToArray();
        }

        private ListItem[] GetViews(Guid id)
        {
            List<ListItem> li = new List<ListItem>();
            SPList list = SPContext.Current.Web.Lists.GetList(id, false); ;
            if (list != null)
            {
                SPViewCollection views = list.Views;
                foreach (SPView view in views)
                {
                    li.Add(new ListItem(view.Title, view.ID.ToString()));
                }
            }
            return li.ToArray();
        }

        private Dictionary<string, string> ValidateFields(string template, Guid ListName)
        {
            Dictionary<string, string> keys = new Dictionary<string, string>();
            try
            {

                SPList list = SPContext.Current.Web.Lists.GetList(ListName, true); ;
                foreach (SPField field in list.Fields)
                {
                    if (template.IndexOf(string.Format("[{0}]", field.InternalName)) >= 0)
                    {
                        if (keys.ContainsKey(string.Format("[{0}]", field.InternalName))) continue;
                        keys.Add(string.Format("[{0}]", field.InternalName), field.InternalName);
                    }
                }
            }
            catch 
            {
                
            }
            return keys;
        }

    }
}
